#include <unistd.h>
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>
using std::cout;
using std::endl;
using std::string;
void Usage(const std::string &proc)
{
    cout << "\n\rUsage: " << proc << ": ip port" << endl;
}
string ip = "127.0.0.1";
uint16_t port = 8080;
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(-1);
    }
    port = atoi(argv[2]);
    ip = argv[1];
    struct sockaddr_in addr;
    bzero(&addr, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = inet_addr(ip.c_str());
    socklen_t len = sizeof(addr);

    while (true)
    {
        int cnt = 5;
        bool isre = false;
        int socketfd = socket(AF_INET, SOCK_STREAM, 0);
        if (socketfd < 0)
        {
            cout << "socket error\n";
            exit(-2);
        }
        do
        {
            int n = connect(socketfd, (sockaddr *)&addr, len);
            if (n < 0)
            {
                cout << "connect error,reconnect cnt:" << cnt << endl;
                isre = true;
                --cnt;
                sleep(1);
            }
            else
            {
                break;
            }
        } while (cnt && isre);
        if (cnt == 0)
        {
            cout << "can not connect! quit please!\n";
            exit(-3);
        }

        // while (true)
        // {
        string mes;
        cout << "please Enter@:";
        getline(std::cin, mes);
        // sleep(2);
        int n = write(socketfd, mes.c_str(), sizeof(mes));
        if (n < 0)
        {
            std::cerr << "write error..." << endl;
            // break;
        }
        char buff[1024];
        n = read(socketfd, buff, sizeof(buff));
        if (n > 0)
        {
            buff[n] = '\0';
        }
        // else
        // {
        //     break;
        // }
        cout << buff << endl;

        close(socketfd);
    }
    // }
    return 0;
}
